package api

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"mxshop-api/shared/code"
	"mxshop-api/user-web/dao/redis"
	"mxshop-api/user-web/forms"
	"mxshop-api/user-web/global"
)

type Sender interface {
	Send(phone string, data []string) (err error)
}

func SendSMSCode(c *gin.Context) {
	var smsForm forms.SendSMSForm
	if err := c.ShouldBind(&smsForm); err != nil {
		HandleValidatorError(c, err)
		return
	}

	// 生成随机验证码
	g := code.NewSMSCodeGen()
	smsCode := g.GenerateCode(global.ServerConfig.SMSCodeConfig.Num)

	// 根据不同的type,对应不同的prefix_key,先查询redis中是否存在
	var key string
	ctx := context.Background()
	switch smsForm.Type {
	case 0, 1:
		key = fmt.Sprintf(global.RegisterKeyPrefix, smsForm.Mobile)
		err := redis.GetSet(ctx, key, smsCode, time.Duration(global.ServerConfig.SMSCodeConfig.Expire)*time.Second)
		if err != nil {
			if errors.Is(err, redis.NewExistsErr()) {
				c.JSON(http.StatusBadRequest, gin.H{"msg": "已发送"})
				return
			}
			c.JSON(http.StatusInternalServerError, gin.H{"msg": "服务器异常,请稍后重试"})
			return
		}
	}

	// 发送验证码(测试时注释)
	/*var s Sender = sms.NewSend()
	expireMin := global.ServerConfig.SMSCodeConfig.Expire / 60
	err := s.Send(smsForm.Mobile, []string{smsCode, fmt.Sprintf("%d", expireMin)})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "cannot send sms code"})
		return
	}*/

	zap.L().Info("sms code", zap.String("mobile", smsForm.Mobile), zap.String("code", smsCode))

	c.JSON(http.StatusOK, gin.H{"msg": "success"})
}
